// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const cmd = require('node-cmd');

const python3Path = 'C:/Python38/python.exe';

const exeDir = 'D:/my_tools/GitHelper/';
const exePath = exeDir + 'main.exe';
const pyPath = exeDir + 'find_and_send.py';

const WindowTitle = '3DB34A73-8178-4541-B06B-1E5BFBF2690D';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "helloworld" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('helloworld.helloWorld', function () {
		// The code you place here will be executed every time your command is executed

		const docUri = vscode.window.activeTextEditor.document.uri.toString();
		const docPath = decodeURIComponent(docUri).substring(8); // 去掉 "file://"
		console.log('docPath: ' + docPath);

		let cmd_str = '';

		cmd_str = `tasklist /fi "windowtitle eq ${WindowTitle}" /nh`;
		cmd.run(cmd_str, (err, stdout, stderr) => {
            console.log('cmd: ', stdout);

			let msg = '';

			if (stdout.includes('.exe')) {
				msg = '目标程序已启动';
				// 通过 python 调用 win32api 给目标窗口发消息
				cmd_str = `${python3Path} ${pyPath} ${docPath}`;
				// console.log('cmd_str: ', cmd_str);
				cmd.run(cmd_str, () => {});
			} else {
				msg = '目标程序未启动';
				// 启动目标程序
				cmd_str = `${exePath} -file ${docPath}`;
				// console.log('cmd_str: ', cmd_str);
				cmd.run(cmd_str, () => {});
			}

			console.log(msg);
			vscode.window.showInformationMessage(msg);
		});
	});

	context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
